package com.shaokel.service.impl;

import com.shaokel.config.exception.NotFoundException;
import com.shaokel.pojo.Type;
import com.shaokel.repository.TypeRepository;
import com.shaokel.service.TypeService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 少丶客
 * @ClassName TypeServiceImpl
 * @Description TODO
 * @Date 2020/6/24 15:53
 * @Vesion 1.0
 */
@Service
@Transactional   //开启事物
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository typeRepository;

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    //根据名称查找Type
    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    //增加Type
    @Override
    public Type savaType(Type type) {
        return typeRepository.save(type);
    }

    //删除Type
    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);
    }

    //更新Type
    @Override
    public Type updateType(Long id, Type type) {
        Type t = typeRepository.findById(id).get();
        if(t==null){
            throw new NotFoundException("不存在该类型!");
        }
        return typeRepository.save(type);
    }

    //查找Type
    @Override
    public Type getType(Long id) {
        return typeRepository.findById(id).get();
    }

    //分页查询Type
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeRepository.findTop(pageable);
    }
}